﻿using Yz.Base;
using Yz.Base.ParaModels;
using Yz.Core.Extensions;
using Yz.Core.Tools;
namespace Yz.FileService.Middlewares
{
    /// <summary>
    /// 复制接口
    /// </summary>
    public class CopyMiddleware : BaseUploadMiddleware, IMiddleware
    {
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            #region 跨域上传
            if (context.Request.Method.Equals(HttpMethods.Options, StringComparison.OrdinalIgnoreCase))
            {
                base.AddHttpOptionHeader(context);
            }
            #endregion

            #region 后台post上传
            else if (context.Request.Method.Equals(HttpMethods.Post, StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    #region 验证token
                    var validRes = await ValidateTokenAsync(context);
                    if (!validRes.Item1.IsEmpty())
                    {
                        await context.Response.WriteAsync(new VmUpFileBase()
                        {
                            Msg = validRes.Item1
                        }.ToJsonStr());
                        return;
                    }
                    string appId = validRes.Item2;
                    #endregion

                    var sv = context.Request.Form["application/json"].FirstOrDefault();
                    if (sv.IsEmpty())
                    {
                        sv = context.Request.Form["data"].FirstOrDefault();
                    }
                    string fileId = "";
                    if (!sv.IsEmpty())
                    {
                        var paraFileId = sv.ToJsonObject<ParaFileId>();
                        if (paraFileId == null || string.IsNullOrEmpty(paraFileId.Id))
                        {
                            await context.Response.WriteAsync(new VmUpFileBase()
                            {
                                Msg = "参数不正确！"
                            }.ToJsonStr());
                            return;
                        }
                        fileId = paraFileId.Id;
                    }
                    string filePath = fileId.ToDes3Decrypt();
                    if (!filePath.Contains(appId))
                    {
                        await context.Response.WriteAsync(new VmUpFileBase()
                        {
                            Msg = "您没有权限复制此文件！"
                        }.ToJsonStr());
                        return;
                    }
                    if (!File.Exists(_uploadConfig.PhysicalPath + filePath))
                    {
                        await context.Response.WriteAsync(new VmUpFile()
                        {
                            Msg = "您要复制的文件不存在！"
                        }.ToJsonStr());
                        return;
                    }

                    string fileName = Path.GetFileName(filePath);
                    string ext = fileName.Substring(fileName.LastIndexOf("."));
                    string fileNewName = Guid.NewGuid().ToString("n") + ext;
                    var dtNow = DateTime.Now;
                    string targetPath = "/" + appId + "/" + dtNow.ToString("yyyy") + "/" + dtNow.ToString("MM") + "/" + dtNow.ToString("dd") + "/";
                    string localFolderPath = _uploadConfig.PhysicalPath + targetPath;
                    if (!Directory.Exists(localFolderPath))
                    {
                        Directory.CreateDirectory(localFolderPath);
                    }
                    File.Copy(_uploadConfig.PhysicalPath + filePath, localFolderPath + fileNewName);
                    FileType fileType = FileType.None;
                    if (FileTypeList.ImgList.Contains(ext))
                    {
                        fileType = FileType.Pic;
                    }
                    else if (FileTypeList.DocList.Contains(ext))
                    {
                        fileType = FileType.Doc;
                    }
                    else if (FileTypeList.VdoList.Contains(ext))
                    {
                        fileType = FileType.Vdo;
                    }
                    else if (FileTypeList.RarList.Contains(ext))
                    {
                        fileType = FileType.Rar;
                    }
                    else if (FileTypeList.RdoList.Contains(ext))
                    {
                        fileType = FileType.Rdo;
                    }
                    await context.Response.WriteAsync(new VmUpFile()
                    {
                        Msg = "文件复制成功！",
                        Suc = true,
                        File = new FileUp()
                        {
                            FileSuffix = ext,
                            FileType = fileType,
                            Name = fileNewName,
                            Path = _uploadConfig.VirtualPath + targetPath + fileNewName,
                            Id = (targetPath + fileNewName).ToDes3Encrypt()
                        }
                    }.ToJsonStr());
                    return;
                }
                catch (Exception ex)
                {
                    YzNLog.Error(ex);
                    await context.Response.WriteAsync(new VmUpFileBase()
                    {
                        Msg = "文件复制失败"
                    }.ToJsonStr());
                }
            }
            #endregion

            #region 非法上传
            else
            {
                await base.AddHttpNotAllowedAsync(context);
            }
            #endregion 
        }
    }
}
